<template>
  <div class="search-container" v-loading="loading">
    <el-form v-model="searchPage" inline="true" >
      <el-form-item  v-for="(item, index) in searchPage.items" :key="index" :label="item.cnname">
        <el-select  v-if="item.itemType === 'DICT'" v-model="item.value" :multiple = "item.mutSelect ==='checkBox'">
          <el-option  v-for="(itemChild, itemIndex) in item.dict" :key="itemIndex"  :label="itemChild.value" :value="itemChild.key" />
        </el-select>
        <el-input v-else-if="item.itemType !== 'DATE'" v-model="item.value"></el-input>
        <el-col :span="24" v-else>
          <el-form-item>
            <el-date-picker
              v-model="item.dateValue"
              type="date"
              label="Pick a date"
              placeholder="Pick a date"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onExportData">导出</el-button>
        <el-button type="primary" @click="onNotice">通知</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="data-container">
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="80" label="序号"/>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="userName" label="姓名" width="120" />
      <el-table-column prop="certificateCode" label="证件号" width="180" />
      <el-table-column prop="sex" label="性别" width="100">
        <template #default="scope">
          <el-select v-model="scope.row.sex" placeholder="" name="sex" disabled>
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="60" />
      <el-table-column prop="area" label="区域" width="120" />
      <el-table-column prop="vaccine" label="疫苗" width="240">
        <template #default="scope">
          <el-select v-model="scope.row.vaccine" placeholder="" name="vaccine" disabled>
            <el-option key="0" label="九价HPV疫苗(19-26岁)" value="0"/>
            <el-option key="1" label="四价HPV疫苗(26-45岁）" value="1" />
            <el-option key="2" label="23价肺炎疫苗(18岁及以上)" value="2"/>
            <el-option key="3" label="20ug重组乙肝疫苗(18岁及以上)" value="3" />
            <el-option key="4" label="四价流感疫苗(18岁及以上)" value="4"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="telNo" label="联系方式" width="120" />
      <el-table-column prop="regStatus" label="当前状态" width="120">
        <template #default="scope">
          <el-select v-model="scope.row.regStatus" placeholder="" name="regStatus" disabled>
            <el-option key="0" label="已预约" value="0"/>
            <el-option key="1" label="已通知" value="1" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="noticeDateTime" label="通知时间" width="160" />
      <el-table-column fixed="right" label="操作" width="120">
        <!-- vue3中 solt-scop已经放弃使用 -->
        <template #default="scope">
           <el-button text type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
     <el-pagination
      v-model:currentPage="searchPage.current"
      v-model:page-size="searchPage.pageSize"
      :page-sizes="[20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.total"
      hide-on-single-page=true
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogVisible"
      title="通知"
      width="60%"
    >
      <el-form label-width="360px" label-position="top">
        <el-form-item label="疫苗时间">
          <el-col :span="24">
          <el-form-item>
            <el-date-picker
              v-model="arriveDate"
              type="date"
              label="Pick a date"
              placeholder="Pick a date"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsend()">通知</el-button>
          <!-- <el-button @click="onReset">{{$t('msg.common.reset')}}</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onActivated } from 'vue'
import { list, deleteById, downLoadFile } from '@/api/common/common'
import { exportData, sendSms, exportUrl } from '@/api/single/vaccine'
import { dateToString, dateToNext, dateTimeToString, dToS } from '@/utils/date'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const tableDatas = ref({})

const dialogVisible = ref(false)

const mutSelectDatas = ref([])

const arriveDate = ref(null)

const loading = ref(false)

const i18n = useI18n()

const handleClose = () => {
  dialogVisible.value = false
  arriveDate.value = null
}
const searchPage = ref({
  items: [
    {
      name: 'vaccine',
      cnname: '疫苗',
      itemType: 'DICT',
      sign: '==',
      value: '',
      mutSelect: 'radio',
      dict: [
        {
          key: '0',
          value: '九价HPV疫苗(19-26岁)'
        },
        {
          key: '1',
          value: '四价HPV疫苗(26-45岁）'
        },
        {
          key: '2',
          value: '23价肺炎疫苗(18岁及以上)'
        },
        {
          key: '3',
          value: '20ug重组乙肝疫苗(18岁及以上)'
        },
        {
          key: '4',
          value: '四价流感疫苗(18岁及以上)'
        }
      ]
    },
    {
      name: 'userName',
      cnname: '姓名',
      itemType: 'STRING',
      sign: 'like',
      value: '',
      dateValue: ''
    },
    {
      name: 'createTime1',
      cnname: '开始时间',
      itemType: 'DATE',
      sign: '>=',
      value: dateToString(-7),
      dateValue: dateToNext(-7)
    },
    {
      name: 'createTime2',
      cnname: '结束时间',
      itemType: 'DATE',
      sign: '<=',
      value: dateToString(0),
      dateValue: dateToNext(0)
    }
  ],
  pageSize: 20,
  current: 1,
  sortBy: ['id']
})

const tableData = ref([])

const vaccineEntity = ref({})

const searchFunction = async () => {
  console.log(searchPage.value)
  list(searchPage.value, 'vaccineReg').then(res => {
    tableData.value = res.content
    tableDatas.value.total = parseInt(res.totalElements)
    ElMessage.success('成功')
  }).catch(err => {
    ElMessage.success('失败' || err.message)
  })
}

onActivated(searchFunction())

const onSubmit = () => {
  searchFunction()
}

const onReset = () => {
  searchPage.value = {
    items: [
      {
        name: 'vaccine',
        cnname: '疫苗',
        itemType: 'DICT',
        sign: '==',
        value: '',
        mutSelect: 'radio',
        dict: [
          {
            key: '0',
            value: '九价HPV疫苗(19-26岁)'
          },
          {
            key: '1',
            value: '四价HPV疫苗(26-45岁）'
          },
          {
            key: '2',
            value: '23价肺炎疫苗(18岁及以上)'
          },
          {
            key: '3',
            value: '20ug重组乙肝疫苗(18岁及以上)'
          },
          {
            key: '4',
            value: '四价流感疫苗(18岁及以上)'
          }
        ]
      },
      {
        name: 'userName',
        cnname: '姓名',
        itemType: 'STRING',
        sign: 'like',
        value: '',
        dateValue: ''
      },
      {
        name: 'createTime1',
        cnname: '开始时间',
        itemType: 'DATE',
        sign: '>=',
        value: dateToString(-7),
        dateValue: dateToNext(-7)
      },
      {
        name: 'createTime2',
        cnname: '结束时间',
        itemType: 'DATE',
        sign: '<=',
        value: dateToString(0),
        dateValue: dateToNext(0)
      }
    ],
    pageSize: 20,
    current: 1,
    sortBy: ['id']
  }
  // 处理查询
  searchFunction()
}

const handleSizeChange = pageSize => {
  searchPage.value.pageSize = pageSize
  // 执行查询操作
  searchFunction()
}

const handleCurrentChange = current => {
  searchPage.value.current = current
  // 执行查询操作
  searchFunction()
}

const handleClick = row => {
  dialogVisible.value = true
  vaccineEntity.value = row
  vaccineEntity.value.provideDateTime = dateTimeToString(0)
}

const handleDelete = row => {
  loading.value = true
  deleteById(row.id, 'vaccineReg').then(res => {
    loading.value = false
    ElMessage.success('成功')
    searchFunction()
  }).catch(err => {
    loading.value = false
    ElMessage.error(err.message)
  })
}

const downLoadXls = content => {
  // const blob = new Blob([content])
  const blob = [content]
  const fileName = new Date().getMinutes() + '.xlsx'
  // 这是设置表格的文件名
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    // 释放URL 对象
    document.body.removeChild(elink)
  } else {
    // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}

const onExportData = () => {
  exportUrl(dToS(searchPage.value.items[2].dateValue), dToS(searchPage.value.items[3].dateValue), searchPage.value.items[0].value ? searchPage.value.items[0].value : 0).then(content => {
    const blob = new Blob([content], { type: 'application/vnd.ms-excel' })
    const fileName = new Date().getMinutes() + '.xlsx'
    // 这是设置表格的文件名
    if ('download' in document.createElement('a')) {
      // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      const binaryData = []
      binaryData.push(blob)
      elink.href = window.URL.createObjectURL(new Blob(binaryData))
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

const onNotice = () => {
  console.log(mutSelectDatas.value)
  if (mutSelectDatas.value.length < 1) {
    ElMessage.info('请选择需要发送消息的患者！！！！')
    return
  }
  dialogVisible.value = !dialogVisible.value
}

const handleSelectionChange = vals => {
  mutSelectDatas.value = vals
}

const onsend = () => {
  if (arriveDate.value) {
    // 执行发送数据
    const ids = []
    mutSelectDatas.value.forEach(date => {
      ids.push(date.id)
    })
    console.log(arriveDate.value)
    sendSms(dToS(arriveDate.value), ids).then(res => {
      ElMessage.success(res.message)
      arriveDate.value = null
    }).catch(err => {
      ElMessage.error(err.message)
    })
  } else {
    // 没有填写时间
  }
}
</script>

<style scope>
.search-container {
  width: 100%;
  height: 100px;
}
</style>
